package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Banner;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.query.BannerQuery;
import cn.wolfcode.luowowo.repository.BannerRepository;
import cn.wolfcode.luowowo.service.IBannerService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class BannerServiceImpl implements IBannerService {


    @Autowired
    private BannerRepository bannerRepository;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Banner banner) {
        banner.setId(null);
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {

        bannerRepository.save(banner);

    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);

    }

    @Override
    public Banner get(String id) {
        Optional<Banner> op = bannerRepository.findById(id);
        if (op.isPresent()) {
            Banner banner = op.get();
            return banner;
        }
        return null;

    }


    @Override
    public List<Banner> list()
    {
        return bannerRepository.findAll();
    }


    // 分页操作
    @Override
    public Page<Banner> query(BannerQuery qo) {

        Query query = new Query();
        // 查询总页数
        long count = mongoTemplate.count(query, Banner.class);
        if (count == 0){
            return Page.empty();
        }

        // 分页排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "_id");

        // 查询总条件
        query.with(pageable);

        // 拿到所有对象的集合
        List<Banner> list = mongoTemplate.find(query, Banner.class);


        // 返回
        return new PageImpl<>(list,pageable,count);

    }

    /**
     * 首页显示游记前五的
     * @return
     */
    @Override
    public List<Banner> queryTravelByType() {
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.ASC, "sequence");
        List<Banner> list = bannerRepository.findByType(Banner.TYPE_TRAVEL, pageable);
        return list;
    }

    /**
     * 首页显示攻略第一的
     * @return
     */
    @Override
    public List<Banner> queryStrategyByType() {
        Pageable pageable = PageRequest.of(0, 1, Sort.Direction.ASC, "sequence");
        List<Banner> list = bannerRepository.findByType(Banner.TYPE_STRATEGY,pageable);
        return list;
    }


}
